<template>
  <div>
    <h2>题型管理</h2>
    <el-table :data="originalQuestionTypes" stripe style="width: 100%; margin-bottom: 20px;">
      <el-table-column prop="type_id" label="题型ID" width="80"></el-table-column>
      <el-table-column prop="type_name" label="题型名称"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openCustomTypeDialog(scope.row)">自定义题型</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 自定义题型表格 -->
    <el-table :data="customQuestionTypes" stripe style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="custom_id" label="自定义ID" width="80"></el-table-column>
      <el-table-column prop="custom_name" label="自定义题型名称"></el-table-column>
      <el-table-column label="基础原始题型" prop="base_type"></el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="editCustomType(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteCustomType(scope.row.custom_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 10px;">
      <el-button type="danger" @click="batchDeleteCustomTypes" :disabled="selectedCustomTypes.length === 0">批量删除</el-button>
    </div>

    <!-- 自定义题型对话框 -->
    <el-dialog :title="isEditing ? '修改自定义题型' : '新增自定义题型'" :visible.sync="dialogVisible">
      <el-form ref="form" :model="currentCustomType" :rules="formRules" label-width="140px" label-position="right">
        <el-form-item prop="custom_name" label="自定义题型名称">
          <el-input v-model="currentCustomType.custom_name"></el-input>
        </el-form-item>

        <el-form-item label="基础原始题型">
          <el-select v-model="currentCustomType.base_type" placeholder="选择原始题型">
            <el-option
                v-for="type in originalQuestionTypes"
                :key="type.type_id"
                :label="type.type_name"
                :value="type.type_name"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request';

export default {
  data() {
    return {
      originalQuestionTypes: [],
      customQuestionTypes: [],
      dialogVisible: false,
      isEditing: false,
      selectedCustomTypes: [],
      currentCustomType: {
        custom_id: null,
        custom_name: '',
        base_type: '',
      },
      formRules: {
        custom_name: [
          {required: true, message: '请输入自定义题型名称', trigger: ['blur', 'change']},
          {min: 1, message: '自定义题型名称不能为空', trigger: 'blur'},
          {max: 50, message: '自定义题型名称不能超过50个字符', trigger: 'blur'},
          {
            pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
            message: '自定义题型名称只能包含字母、数字和中文字符',
            trigger: 'blur'
          }
        ],
      },
      teacherId: localStorage.getItem('teacherId'),
    };
  },
  created() {
    this.fetchOriginalQuestionTypes();
    this.fetchCustomQuestionTypes();
  },
  methods: {
    async fetchOriginalQuestionTypes() {
      try {
        const response = await axios.get('/originalQuestionType');
        this.originalQuestionTypes = response.data;
      } catch (error) {
        console.error('获取原始题型失败:', error);
      }
    },
    async fetchCustomQuestionTypes() {
      try {
        const response = await axios.get(`/customQuestionType/${this.teacherId}`);
        this.customQuestionTypes = response.data;
      } catch (error) {
        console.error('获取自定义题型失败:', error);
      }
    },
    openCustomTypeDialog(baseType) {
      this.isEditing = false;
      this.currentCustomType = {
        custom_id: this.customQuestionTypes.length + 1,
        custom_name: '',
        base_type: baseType.type_name,
        teacherId: this.teacherId,
      };
      this.dialogVisible = true;
    },
    // 编辑自定义题型
    editCustomType(row) {
      this.isEditing = true;
      this.currentCustomType = {...row};
      this.dialogVisible = true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveCustomType();
        } else {
          this.$message.error('表单校验失败，请检查输入项！');
        }
      });
    },
    async saveCustomType() {
      if (this.isEditing) {
        try {
          await axios.put(`/customQuestionType/${this.currentCustomType.custom_id}`, this.currentCustomType);
          await this.fetchCustomQuestionTypes();
          this.$message({
            message: '题型修改成功',
            type: 'success',
            offset: '80' // 偏移量
          });
        } catch (error) {
          this.$nextTick(() => {
            this.$message.error('题型修改失败');
          });
        }
      } else {
        try {
          await axios.post('/customQuestionType', this.currentCustomType);
          await this.fetchCustomQuestionTypes();
            this.$message({
              message:'题型创建成功',
              type: 'success',
              offset: '80'
            });
        } catch (error) {
          this.$nextTick(() => {
            this.$message.error('题型创建失败');
          });
        }
      }
      this.dialogVisible = false;
    },
    async deleteCustomType(customId) {
      try {
        await axios.delete(`/customQuestionType/${customId}`);
        await this.fetchCustomQuestionTypes();
        // 确保页面更新后再显示消息
        this.$nextTick(() => {
          this.$message({
            message:'题型删除成功',
            type: 'success',
            offset: '80'
          })
        });
      } catch (error) {
        this.$nextTick(() => {
          this.$message.error('题型删除失败');
        });
      }
    },
    // 批量删除自定义题型
    async batchDeleteCustomTypes() {
      const deletePromises = this.selectedCustomTypes.map((type) =>
          axios.delete(`/customQuestionType/${type.custom_id}`)
      );
      try {
        await Promise.all(deletePromises);
        await this.fetchCustomQuestionTypes();
          this.$message({
            message:'批量删除成功',
            type: 'success',
            offset: '80'
          });
        this.selectedCustomTypes = [];
      } catch (error) {
        this.$nextTick(() => {
          this.$message.error('批量删除失败');
        });
      }
    },
    handleSelectionChange(val) {
      this.selectedCustomTypes = val;
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
